import os

import jieba
from jieba import analyse

from db.dao import NewsDao
from db.models import News

project_path = os.path.abspath(os.path.dirname(__file__))
jieba.load_userdict(project_path + r'/stock_dict.txt')
analyse.set_stop_words(project_path + r'/stopwords.txt')


def analysis(news_id):
    if news_id :
        news_list = news_id.split(',')
        for id in news_list:
            news = NewsDao().findById(id)
            if news:
                content = getattr(news, 'content')
                if not content:
                    content=getattr(news,'title')
                if content:
                    tags = analyse.extract_tags(content)
                    new_key = News()
                    setattr(new_key, 'id', id)
                    setattr(new_key, 'keys', ','.join(tags))
                    NewsDao().updateById(new_key)
    else:
        news_list = NewsDao().findByKeysNone()
        if news_list:
            for news in news_list:
                content = getattr(news, 'content')
                if not content:
                    content = getattr(news, 'title')
                if content:
                    tags = analyse.extract_tags(content)
                    new_key = News()
                    setattr(new_key, 'id', getattr(news,'id'))
                    setattr(new_key, 'keys', ','.join(tags))
                    NewsDao().updateById(new_key)


if __name__ == '__main__':
    analysis()
